<?php

namespace services\patient;

use common\models\base\Project;
use Yii;
use common\components\Service;
use common\models\patient\Consumption;

/**
 * Class ConsumptionService
 * @package services\patient
 */
class ConsumptionService extends Service
{
    /**
     * 根据ID查找信息
     *
     * @param int $id
     * @return Consumption|null
     */
    public function findById(int $id = 0): ?Consumption
    {
        return Consumption::find()->where(['id' => $id])->one();
    }

    /**
     * 查找信息
     *
     * @param array $condition
     * @return Consumption|null
     */
    public function findInfo(array $condition = []): ?Consumption
    {
        $query = Consumption::find();

//        isset($condition['body_parts_id']) && $query->andWhere(['body_parts_id' => $condition['body_parts_id']]);

        return $query->one();
    }

    /**
     * 查找列表
     *
     * @param array $condition
     * @return array|\yii\db\ActiveRecord[]
     */
    public function findList(array $condition = [])
    {
        $query = Consumption::find();

        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);

        return $query->asArray()->all();
    }

    /**
     * 患者消费信息列表
     *
     * @param array $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getListPage(array $params = [], int $page = 0, int $pageSize = 0)
    {
        $query = Consumption::find()->select(['*'])
            ->where([
                'project_id' => $params['project_id'],
                'patient_card_id' => $params['patient_card_id'],
            ]);

        $query->orderBy(['clinic_time' => SORT_DESC, 'id' => SORT_DESC]);

        // 总数
        $total = $query->count();

        // 分页
        if ($page && $pageSize) {
            $query->limit($pageSize)->offset(($page - 1) * $pageSize);
        }

        $list = $query->asArray()->all();

        return [
            'page' => (int)$page,
            'pageSize' => (int)$pageSize,
            'total' => (int)$total,
            'list' => $list,
        ];
    }

    /**
     * 格式化列表数据
     *
     * @param array $data
     * @param int $type
     * @return array
     */
    public function getListPageFormat(array $data)
    {
        $list = [];
        foreach ($data as $row) {
            $item = [
                'id' => $row['id'],
                'project_id' => $row['project_id'],
                'patient_card_id' => $row['patient_card_id'],
                'consulting_room' => $row['consulting_room'],
                'doctor_name' => $row['doctor_name'],
                'money' => $row['trade_type'] == Consumption::TRADE_TYPE_REFUND ? '-'.abs($row['money']) : abs($row['money']),
//                'reality_money' => $row['trade_type'] == Consumption::TRADE_TYPE_REFUND ? '-'.abs($row['refund_money']) : abs($row['reality_money']),
                'reality_money' => $row['reality_money'],
                'trade_type' => $row['trade_type'],
                'clinic_time_str' => $row['clinic_time'] ? date('Y-m-d', $row['clinic_time']) : '',
                'created_at_str' => $row['created_at'] ? date('Y-m-d H:i', $row['created_at']) : '',
            ];

            $list[] = $item;
        }

        return $list;
    }

    /**
     * 患者消费明细
     *
     * @param array $params
     * @return int|mixed
     */
    public function getPatientPayMoney(array $params = [])
    {
        $res = Consumption::find()->select(['SUM(reality_money) AS reality_money'])
            ->where([
                'project_id' => $params['project_id'],
                'patient_card_id' => $params['patient_card_id'],
            ])
            ->groupBy('patient_card_id')
            ->asArray()
            ->one();

        return $res ? $res['reality_money'] : 0;
    }

    public function getDtList(array $params): array
    {
        return Consumption::find()
            ->select(['sum(reality_money) as money', 'patient_card_id'])
            ->where([
                'project_id' => $params['project_id'],
                'patient_card_id' => $params['patient_card_id'],
            ])
            ->andWhere(['<', 'clinic_time', $params['end_time']])
            ->groupBy('patient_card_id')
            ->asArray()
            ->all();
    }

    public function getDtList1(array $params): array
    {
        $query = Consumption::find()->alias('a')
            ->select('sum(a.reality_money) reality_money, a.patient_card_id, a.project_id')
            ->leftJoin(Project::tableName() . ' p', 'a.project_id=p.id')
            ->where([
                'a.patient_card_id' => $params['patient_card_id_arr'],
                'p.name_sx' => $params['project_id_arr'],
            ]);
        if (isset($params['matching']) && $params['matching']) {// 单独点击同步时（指定患者同步）去除时间限制
            if ($params['type'] == 1) {
                $query->andWhere([
                    'and',
                    ['>=', 'a.created_at', $params['start_time']],
                    ['<=', 'a.created_at', $params['end_time']],
                ]);
            } /*else { // 每月1号跑上个月最后一天数据没有，直接去掉
                $query->andWhere([
                    'and',
                    ['>=', 'a.created_at', $month_start_time],
                    ['<=', 'a.created_at', $month_end_time],
                ]);
            }*/
        }

        return $query->groupBy(['a.patient_card_id', 'a.project_id'])
            ->asArray()
            ->all();
    }

    public function getDtList2(array $params): array
    {
        return Consumption::find()
            ->select(['reality_money', 'clinic_time'])
            ->where([
                'patient_card_id' => $params['patientCardId'],
                'project_id' => $params['projectId']
            ])
            ->andWhere(['between', 'clinic_time', strtotime(date('Y-01-01', $params['regTime'])), strtotime(date('Y-12-t 23:59:59', $params['regTime']))])
            ->asArray()
            ->all();
    }
}
